<?php

namespace app\service\traits;

use app\service\UploadService;
use app\Request;
use think\Response;

trait UploadTrait
{
    public function upload(Request $request): Response
    {
        if(!$request->isPost()) return $this->error('当前请求不合法！');

        $data         = [
            'upload_type' => $request->post('upload_type'),
            'file'        => $request->file('file')
        ];
        $uploadConfig = config('oss');

        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];

        $upload_type = $uploadConfig['upload_type'];
        try {
            $upload = UploadService::instance()->setConfig($uploadConfig)->$upload_type($data['file']);
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        $code = $upload['code'] ?? 0;
        if($code == 0) {
            return $this->error('上传失败'.$upload['data'] ?? '');
        }
        return $this->success('上传成功',$upload['data'] ?? '');
    }
}